<template>
  <div class="edit-page-wrap">
    <Head title="型号信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="150px"
          class="edit-form-wrap"
        >
          <el-form-item label="电桩品牌" prop="equipmentBrandId">
            <qc-select
              :value="ruleForm.equipmentBrandId"
              :remote="true"
              :filterable="true"
              :options="optionsS.equipmentBrand"
              placeholder="请选择电桩品牌"
              @change="handleChangeBrand"
            >
            </qc-select>
          </el-form-item>
          <el-form-item label="电桩型号" prop="equipmentModel">
            <el-input
              v-model.trim="ruleForm.equipmentModel"
              placeholder="请输入电桩型号"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="终端数量" prop="number">
            <el-input
              v-model.trim="ruleForm.number"
              placeholder="请输入终端数量"
              maxlength="9"
              clearable
            />
          </el-form-item>
          <el-form-item label="电桩类型" prop="type">
            <el-radio-group
              v-model="ruleForm.type"
              v-for="(item, index) in optionsS.equipmentModelType"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="设备图片" prop="img">
            <QcUpload
              :valueModel="ruleForm.img"
              @on-success="handleSuccessLogo"
              @before-upload="beforeUploadLogo"
              @on-error="handleErrorLogo"
              tip="温馨提示：只能上传jpg/jpeg/png文件，且不超过2M"
            ></QcUpload>
          </el-form-item>
          <el-form-item label="备注说明" prop="remark">
            <el-input
              v-model.trim="ruleForm.remark"
              placeholder="请输入备注说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line"></div>
    <Head title="电桩工作信息">
      <template #content>
        <el-form
          ref="ruleFormOtherRef"
          :model="ruleForm"
          :rules="rules"
          label-width="150px"
          class="edit-form-wrap"
        >
          <el-form-item label="电桩功率" prop="power">
            <el-input
              v-model.trim="ruleForm.power"
              placeholder="请输入电桩功率"
              maxlength="9"
              clearable
            >
              <template #append>kW</template>
            </el-input>
          </el-form-item>
          <el-form-item label="辅助电源" prop="supPower">
            <qc-select
              :value="ruleForm.supPower"
              :options="optionsS.supPowerData"
              placeholder="请选择设备辅助电源"
              @change="handleChangeSupPower"
            >
              <template #append>V</template>
            </qc-select>
          </el-form-item>
          <el-form-item label="额定电流" prop="current">
            <el-input
              v-model.trim="ruleForm.current"
              maxlength="9"
              placeholder="请输入额定电流"
              clearable
            >
              <template #append>A</template>
            </el-input>
          </el-form-item>
          <el-form-item label="输入电压" prop="inputv">
            <el-input
              v-model.trim="ruleForm.inputv"
              maxlength="9"
              placeholder="请填写设备输入电压"
              clearable
            >
              <template #append>V</template>
            </el-input>
          </el-form-item>
          <div style="display: flex; line-height: 36px; font-size: 13px">
            <el-form-item label="额定电压上下限" prop="voltageLowerLimits">
              <el-input
                v-model.trim="ruleForm.voltageLowerLimits"
                maxlength="9"
                placeholder="电压下限"
                clearable
              >
                <template #append>V</template>
              </el-input>
            </el-form-item>
            至
            <el-form-item
              label=""
              prop="voltageUpperLimits"
              style="margin-left: -170px"
            >
              <el-input
                v-model.trim="ruleForm.voltageUpperLimits"
                maxlength="9"
                placeholder="电压上限"
                clearable
              >
                <template #append>V</template>
              </el-input>
            </el-form-item>
          </div>
          <el-form-item label="是否支持有序充电" prop="sautoPower">
            <el-radio-group
              v-model="ruleForm.sautoPower"
              v-for="(item, index) in optionsS.sautoPowerData"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否自动识别VIN" prop="svin">
            <el-radio-group
              v-model="ruleForm.svin"
              v-for="(item, index) in optionsS.svinData"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line"></div>
    <Head title="电桩工作信息">
      <template #content>
        <el-form
          ref="ruleFormOtherRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="150px"
          class="edit-form-wrap"
        >
          <el-form-item label="枪线温度预警" prop="gunTemperatureWarn">
            <el-input
              v-model.trim="ruleForm.gunTemperatureWarn"
              maxlength="9"
              placeholder="请输入枪线温度预警"
              clearable
            >
              <template #append>℃</template>
            </el-input>
          </el-form-item>
          <el-form-item label="枪线温度断充" prop="gunTemperatureStop">
            <el-input
              v-model.trim="ruleForm.gunTemperatureStop"
              maxlength="9"
              placeholder="请输入枪线温度断充"
              clearable
            >
              <template #append>℃</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最大电压" prop="maxv">
            <el-input
              v-model.trim="ruleForm.maxv"
              placeholder="请输入设备最大输出电压"
              maxlength="9"
              clearable
            >
              <template #append>V</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最小电压" prop="minv">
            <el-input
              v-model.trim="ruleForm.minv"
              placeholder="请输入设备最小输出电压"
              maxlength="9"
              clearable
            >
              <template #append>V</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最大电流" prop="maxa">
            <el-input
              v-model.trim="ruleForm.maxa"
              maxlength="9"
              placeholder="请输入设备最大输出电流"
              clearable
            >
              <template #append>A</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最小电流" prop="mina">
            <el-input
              v-model.trim="ruleForm.mina"
              maxlength="9"
              placeholder="请输入设备最小输出电流"
              clearable
            >
              <template #append>A</template>
            </el-input>
          </el-form-item>
          <div style="display: flex; line-height: 36px; font-size: 13px">
            <el-form-item label="恒功率输出电压区间" prop="minp">
              <el-input
                v-model.trim="ruleForm.minp"
                maxlength="9"
                placeholder="电压下限"
                clearable
              >
                <template #append>V</template>
              </el-input>
            </el-form-item>
            至
            <el-form-item label="" prop="maxp" style="margin-left: -170px">
              <el-input
                v-model.trim="ruleForm.maxp"
                maxlength="9"
                placeholder="电压上限"
                clearable
              >
                <template #append>V</template>
              </el-input>
            </el-form-item>
          </div>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import QcUpload from '@/components/qcUpload/index.vue';
import {
  queryAllEquipmentBrand,
  updateEquipmentModel,
  addEquipmentModel,
  queryEquipmentModel,
} from '@/service/apis/config';
import { queryDicByParent } from '@/service/apis/api';
import { IS_INT, IS_NUM1 } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const ruleFormRef = ref<FormInstance>();
const ruleFormOtherRef = ref<FormInstance>();
const ruleFormOtherRef1 = ref<FormInstance>();

const errLogo = ref('');
const checkLogo = (rule: any, value: any, callback: any) => {
  if (!value) {
    if (errLogo.value === 'type') {
      callback(new Error('上传的图片格式不正确'));
    } else if (errLogo.value === 'size') {
      callback(new Error('上传的图片大于2M'));
    } else if (errLogo.value === 'error') {
      callback(new Error('上传失败'));
    }
  }
  callback();
};

// 设备图片
const handleSuccessLogo = (val: any) => {
  ruleForm.img = val;
  ruleFormRef?.value?.validateField('img');
};
const handleErrorLogo = () => {
  errLogo.value = 'error';
  ruleFormOtherRef?.value?.validateField('img');
};
const beforeUploadLogo = (type: string) => {
  errLogo.value = type;
  if (type) {
    ruleFormRef?.value?.validateField('img');
  }
};

let optionsS = reactive({
  equipmentBrand: [] as any,
  equipmentModelType: [] as any,
  supPowerData: [] as any,
  sautoPowerData: [] as any,
  svinData: [] as any,
});

// 电桩品牌
queryAllEquipmentBrand({}).then((res: any) => {
  if (res) {
    nextTick(() => {
      optionsS.equipmentBrand = [...res];
    });
  }
});

// 字典
queryDicByParent({
  listDtos: ['equipmentModelType', 'supPower', 'sautoPower', 'svin'],
}).then((res: any) => {
  optionsS.equipmentModelType = res.equipmentModelType;
  optionsS.supPowerData = res.supPower;
  optionsS.sautoPowerData = res.sautoPower;
  optionsS.svinData = res.svin;
});

const handleChangeBrand = (e: any) => {
  ruleForm.equipmentBrandId = e;
};

const handleChangeSupPower = (e: any) => {
  ruleForm.supPower = e;
};

const checkVoltage = (rule: any, value: any, callback: any) => {
  if (ruleForm.maxv && ruleForm.minv) {
    if (Number(ruleForm.maxv) > Number(ruleForm.minv)) {
      ruleFormOtherRef.value?.clearValidate('maxv');
      ruleFormOtherRef.value?.clearValidate('minv');
    } else {
      callback(new Error('最大电压须大于最小电压'));
    }
  }
  callback();
};

const checkCurrent = (rule: any, value: any, callback: any) => {
  if (ruleForm.maxa && ruleForm.mina) {
    if (Number(ruleForm.maxa) > Number(ruleForm.mina)) {
      ruleFormOtherRef.value?.clearValidate('maxa');
      ruleFormOtherRef.value?.clearValidate('mina');
    } else {
      callback(new Error('最大电流须大于最小电流'));
    }
  }
  callback();
};

const checkPower = (rule: any, value: any, callback: any) => {
  if (ruleForm.maxp && ruleForm.minp) {
    if (Number(ruleForm.maxp) > Number(ruleForm.minp)) {
      ruleFormOtherRef.value?.clearValidate('maxp');
      ruleFormOtherRef.value?.clearValidate('minp');
    } else {
      callback(new Error('电压下限须小于电压上限'));
    }
  }
  callback();
};

const checkVoltageLower = (rule: any, value: any, callback: any) => {
  if (ruleForm.voltageUpperLimits && ruleForm.voltageLowerLimits) {
    if (
      Number(ruleForm.voltageUpperLimits) > Number(ruleForm.voltageLowerLimits)
    ) {
      ruleFormOtherRef.value?.clearValidate('voltageUpperLimits');
      ruleFormOtherRef.value?.clearValidate('voltageLowerLimits');
    } else {
      callback(new Error('电压下限须小于电压上限'));
    }
  }
  callback();
};

let ruleForm: any = reactive({
  id: '',
  equipmentBrandId: undefined as unknown,
  equipmentModel: '',
  number: '',
  type: '',
  img: '',
  remark: '',
  power: '',
  supPower: undefined as unknown,
  current: '',
  inputv: '',
  voltageLowerLimits: '',
  voltageUpperLimits: '',
  sautoPower: '',
  svin: '',
  gunTemperatureWarn: '',
  gunTemperatureStop: '',
  maxv: '',
  minv: '',
  maxa: '',
  mina: '',
  maxp: '',
  minp: '',
});

const rules = reactive<FormRules>({
  equipmentBrandId: [
    { required: true, message: '请选择电桩品牌', trigger: 'change' },
  ],
  equipmentModel: [
    { required: true, message: '请输入电站型号', trigger: 'blur' },
  ],
  number: [
    { required: true, message: '请输入终端数量', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入大于0的正整数',
      trigger: 'blur',
    },
  ],
  type: [{ required: true, message: '请选择电桩类型', trigger: 'change' }],
  power: [
    { required: true, message: '请输入电桩功率', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
  ],
  supPower: [
    { required: true, message: '请选择设备辅助电源', trigger: 'change' },
  ],

  current: [
    { required: true, message: '请输入额定电流', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入大于0的正整数',
      trigger: 'blur',
    },
  ],
  voltageLowerLimits: [
    { required: true, message: '请输入电压下限', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入大于0的正整数',
      trigger: 'blur',
    },
    { validator: checkVoltageLower, trigger: 'blur' },
  ],
  voltageUpperLimits: [
    { required: true, message: '请输入电压上限', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入大于0的正整数',
      trigger: 'blur',
    },
    { validator: checkVoltageLower, trigger: 'blur' },
  ],
  sautoPower: [
    { required: true, message: '请选择是否支持有序充电', trigger: 'change' },
  ],
  svin: [
    { required: true, message: '请选择是否自动识别VIN', trigger: 'change' },
  ],
  gunTemperatureWarn: [
    { required: false, message: '请输入枪线温度预警', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
  ],
  gunTemperatureStop: [
    { required: false, message: '请输入枪线温度断充', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
  ],
  inputv: [
    { required: false, message: '请填写设备输入电压', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
  ],
  maxv: [
    { required: false, message: '请输入设备最大输出电压', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
    { validator: checkVoltage, trigger: 'blur' },
  ],
  minv: [
    { required: false, message: '请输入设备最小输出电压', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
    { validator: checkVoltage, trigger: 'blur' },
  ],
  maxa: [
    { required: false, message: '请输入设备最大输出电流', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
    { validator: checkCurrent, trigger: 'blur' },
  ],
  mina: [
    { required: false, message: '请输入设备最小输出电流', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
    { validator: checkCurrent, trigger: 'blur' },
  ],
  minp: [
    { required: false, message: '请输入电压下限', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
    { validator: checkPower, trigger: 'blur' },
  ],
  maxp: [
    { required: false, message: '请输入电压上限', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
    { validator: checkPower, trigger: 'blur' },
  ],
  img: [{ validator: checkLogo, trigger: 'change' }],
  remark: [{ required: false, message: '请输入备注', trigger: 'blur' }],
});

// 返回
const back = () => {
  router.go(-1);
};

// 编辑回填数据
if (id) {
  queryEquipmentModel({
    id: id,
  }).then((res: any) => {
    for (const key in ruleForm) {
      if (res[key]) {
        ruleForm[key] = res[key];
      }
    }
    ruleForm.type = res.type ? res.type.toString() : '';
    ruleForm.svin = String(res.svin) || '';
    ruleForm.sautoPower = String(res.sautoPower) || '';

    console.log('ruleForm---', ruleForm);
  });
}

// 新增/修改提交
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormOtherRef.value || !ruleFormOtherRef1.value)
    return;
  errLogo.value = '';
  try {
    await Promise.all([
      ruleFormRef.value.validate(),
      ruleFormOtherRef.value.validate(),
      ruleFormOtherRef1.value.validate(),
    ]);
  } catch (fields: any) {
    for (const key in ruleForm) {
      if (fields[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormOtherRef.value.scrollToField(key);
        ruleFormOtherRef1.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  console.log('ruleForm---', ruleForm);
  if (id) {
    ruleForm.id = id;
    updateEquipmentModel(ruleForm).then((res: any) => {
      if (res) {
        emit('clear-cache');
        back();
      }
    });
  } else {
    addEquipmentModel(ruleForm).then((res: any) => {
      if (res) {
        emit('clear-cache');
        back();
      }
    });
  }
};
</script>
<style lang="scss">
.main-wrap .edit-page-wrap .edit-form-wrap .el-input {
  margin: 4px;
}
</style>